$(document).ready(function() {
    // 获取DOM元素
    const canvas = document.getElementById('editor-canvas');
    const ctx = canvas.getContext('2d');
    const uploadImageBtn = $('#upload-image');
    const clearImagesBtn = $('#clear-images');
    const imageInput = $('#image-input');
    const imageList = $('#image-list');
    const uploadStickerBtn = $('#upload-sticker');
    const clearStickersBtn = $('#clear-stickers');
    const stickerInput = $('#sticker-input');
    const stickerList = $('#sticker-list');
    const completeBtn = $('#complete-btn');

    // 数据存储
    let images = [];          // 存储上传的图片
    let stickers = [];        // 存储上传的贴纸
    let currentImage = null;  // 当前编辑的图片
    let currentStickers = []; // 当前画布上的贴纸
    let selectedSticker = null; // 当前选中的贴纸
    let isDragging = false;   // 是否正在拖动
    let isResizing = false;   // 是否正在调整大小
    let dragOffset = { x: 0, y: 0 };
    let animationFrameId = null; // 动画帧ID

    // 图片缓存
    const imageCache = {};
    const stickerCache = {};

    // 初始化画布
    function initCanvas() {
        canvas.width = 800;
        canvas.height = 600;
        ctx.fillStyle = 'white';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    }

    // 上传图片
    uploadImageBtn.click(() => imageInput.click());
    imageInput.change(function(e) {
        const files = e.target.files;
        if (files.length === 0) return;

        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const reader = new FileReader();

            reader.onload = function(event) {
                const img = new Image();
                img.onload = function() {
                    images.push({
                        id: Date.now() + i,
                        src: event.target.result,
                        width: img.width,
                        height: img.height
                    });
                    renderImageList();
                };
                img.src = event.target.result;
            };

            reader.readAsDataURL(file);
        }

        // 清空input值，以便能重复选择同一文件
        this.value = '';
    });

    // 清空图片
    clearImagesBtn.click(() => {
        images = [];
        currentImage = null;
        currentStickers = [];
        renderImageList();
        redrawCanvas();
    });

    // 渲染图片列表
    function renderImageList() {
        imageList.empty();
        images.forEach(image => {
            const imgContainer = $('<div class="image-item-container"></div>');
            const img = $(`<img src="${image.src}" class="image-item" data-id="${image.id}">`);

            // 保持图片宽高比
            img.on('load', function() {
                $(this).css('height', 'auto');
            });

            // 点击图片加载到画布
            img.click(function() {
                const imgId = parseInt($(this).data('id'));
                loadImageToCanvas(imgId);
                // 高亮选中的图片
                $('.image-item').removeClass('selected');
                $(this).addClass('selected');
            });

            imgContainer.append(img);
            imageList.append(imgContainer);
        });
    }

    // 加载图片到画布
    function loadImageToCanvas(imageId) {
        const image = images.find(img => img.id === imageId);
        if (!image) return;

        currentImage = image;
        currentStickers = [];
        selectedSticker = null;

        // 设置画布大小为图片大小
        canvas.width = image.width;
        canvas.height = image.height;

        // 缓存当前图片
        if (!imageCache[image.id]) {
            const img = new Image();
            img.src = image.src;
            imageCache[image.id] = img;
        }

        redrawCanvas();
    }

    // 上传贴纸
    uploadStickerBtn.click(() => stickerInput.click());
    stickerInput.change(function(e) {
        const files = e.target.files;
        if (files.length === 0) return;

        for (let i = 0; i < files.length; i++) {
            const file = files[i];
            const reader = new FileReader();

            reader.onload = function(event) {
                const img = new Image();
                img.onload = function() {
                    stickers.push({
                        id: Date.now() + i,
                        src: event.target.result,
                        width: img.width,
                        height: img.height
                    });
                    renderStickerList();
                };
                img.src = event.target.result;
            };

            reader.readAsDataURL(file);
        }

        // 清空input值
        this.value = '';
    });

    // 清空贴纸
    clearStickersBtn.click(() => {
        stickers = [];
        renderStickerList();
    });

    // 渲染贴纸列表
    function renderStickerList() {
        stickerList.empty();
        stickers.forEach(sticker => {
            const imgContainer = $('<div class="image-item-container"></div>');
            const img = $(`<img src="${sticker.src}" class="image-item" data-id="${sticker.id}">`);

            // 保持图片宽高比
            img.on('load', function() {
                $(this).css('height', 'auto');
            });

            // 点击贴纸添加到画布
            img.click(function() {
                if (!currentImage) return;

                const stickerId = parseInt($(this).data('id'));
                addStickerToCanvas(stickerId);
            });

            imgContainer.append(img);
            stickerList.append(imgContainer);
        });
    }

    // 添加贴纸到画布
    function addStickerToCanvas(stickerId) {
        const sticker = stickers.find(s => s.id === stickerId);
        if (!sticker || !currentImage) return;

        // 缓存贴纸图片
        if (!stickerCache[sticker.id]) {
            const img = new Image();
            img.src = sticker.src;
            stickerCache[sticker.id] = img;
        }

        // 计算最大宽度和高度（画布的80%）
        const maxWidth = canvas.width * 0.8;
        const maxHeight = canvas.height * 0.8;
        let width = sticker.width;
        let height = sticker.height;

        // 如果贴纸尺寸超过最大限制，按比例缩小
        if (width > maxWidth || height > maxHeight) {
            const aspectRatio = width / height;
            if (width > maxWidth) {
                width = maxWidth;
                height = width / aspectRatio;
            }
            if (height > maxHeight) {
                height = maxHeight;
                width = height * aspectRatio;
            }
        }

        // 创建新贴纸对象
        const newSticker = {
            id: Date.now(),
            src: sticker.src,
            width: width,
            height: height,
            x: (canvas.width - width) / 2,
            y: (canvas.height - height) / 2,
            rotation: 0,
            stickerId: sticker.id, // 引用原始贴纸ID用于缓存
            aspectRatio: width / height // 存储宽高比
        };

        currentStickers.push(newSticker);
        redrawCanvas();
    }

    // 重绘画布
    function redrawCanvas() {
        // 取消上一个动画帧
        if (animationFrameId) {
            cancelAnimationFrame(animationFrameId);
        }

        // 请求新的动画帧
        animationFrameId = requestAnimationFrame(() => {
            // 清空画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            // 绘制当前图片
            if (currentImage) {
                const img = imageCache[currentImage.id];
                if (img.complete) {
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                    // 绘制所有贴纸
                    drawStickers();
                } else {
                    img.onload = function() {
                        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                        drawStickers();
                    };
                }
            }
        });
    }

    // 绘制所有贴纸
    function drawStickers() {
        currentStickers.forEach(sticker => {
            const img = stickerCache[sticker.stickerId];
            if (img.complete) {
                ctx.save();
                ctx.translate(sticker.x + sticker.width / 2, sticker.y + sticker.height / 2);
                ctx.rotate(sticker.rotation * Math.PI / 180);
                ctx.drawImage(img, -sticker.width / 2, -sticker.height / 2, sticker.width, sticker.height);
                ctx.restore();

                // 如果是选中的贴纸，绘制边框
                if (selectedSticker && selectedSticker.id === sticker.id) {
                    drawStickerBorder(sticker);
                }
            } else {
                img.onload = function() {
                    ctx.save();
                    ctx.translate(sticker.x + sticker.width / 2, sticker.y + sticker.height / 2);
                    ctx.rotate(sticker.rotation * Math.PI / 180);
                    ctx.drawImage(img, -sticker.width / 2, -sticker.height / 2, sticker.width, sticker.height);
                    ctx.restore();

                    if (selectedSticker && selectedSticker.id === sticker.id) {
                        drawStickerBorder(sticker);
                    }
                };
            }
        });
    }

    // 绘制贴纸边框
    function drawStickerBorder(sticker) {
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 2;
        ctx.strokeRect(sticker.x, sticker.y, sticker.width, sticker.height);

        // 绘制调整大小的手柄
        ctx.fillStyle = 'blue';
        ctx.beginPath();
        ctx.arc(sticker.x + sticker.width, sticker.y + sticker.height, 5, 0, Math.PI * 2);
        ctx.fill();
    }

    // 鼠标按下事件
    canvas.addEventListener('mousedown', function(e) {
        if (!currentImage) return;

        const rect = canvas.getBoundingClientRect();
        const mouseX = e.clientX - rect.left;
        const mouseY = e.clientY - rect.top;

        // 检查是否点击了贴纸的调整手柄
        for (let i = currentStickers.length - 1; i >= 0; i--) {
            const sticker = currentStickers[i];
            // 检查是否点击了调整手柄
            const handleX = sticker.x + sticker.width;
            const handleY = sticker.y + sticker.height;
            const dx = mouseX - handleX;
            const dy = mouseY - handleY;

            if (dx * dx + dy * dy <= 25) { // 5px的半径
                selectedSticker = sticker;
                isResizing = true;
                dragOffset.x = dx;
                dragOffset.y = dy;
                redrawCanvas();
                return;
            }

            // 检查是否点击了贴纸本身
            if (mouseX >= sticker.x && mouseX <= sticker.x + sticker.width &&
                mouseY >= sticker.y && mouseY <= sticker.y + sticker.height) {
                selectedSticker = sticker;
                isDragging = true;
                dragOffset.x = mouseX - sticker.x;
                dragOffset.y = mouseY - sticker.y;
                redrawCanvas();
                return;
            }
        }

        // 点击空白处取消选择
        selectedSticker = null;
        redrawCanvas();
    });

    // 鼠标移动事件
    canvas.addEventListener('mousemove', function(e) {
        if (!currentImage || (!isDragging && !isResizing) || !selectedSticker) return;

        const rect = canvas.getBoundingClientRect();
        const mouseX = e.clientX - rect.left;
        const mouseY = e.clientY - rect.top;

        if (isDragging) {
            // 更新贴纸位置
            selectedSticker.x = mouseX - dragOffset.x;
            selectedSticker.y = mouseY - dragOffset.y;
            redrawCanvas();
        } else if (isResizing) {
            // 保持宽高比不变
            const aspectRatio = selectedSticker.aspectRatio;
            const newWidth = Math.max(10, mouseX - selectedSticker.x + dragOffset.x);
            const newHeight = Math.max(10, mouseY - selectedSticker.y + dragOffset.y);

            // 根据宽高比计算新的尺寸
            const widthBasedHeight = newWidth / aspectRatio;
            const heightBasedWidth = newHeight * aspectRatio;

            // 选择更接近鼠标位置的尺寸
            if (Math.abs(widthBasedHeight - newHeight) < Math.abs(heightBasedWidth - newWidth)) {
                selectedSticker.width = newWidth;
                selectedSticker.height = widthBasedHeight;
            } else {
                selectedSticker.width = heightBasedWidth;
                selectedSticker.height = newHeight;
            }

            redrawCanvas();
        }
    });

    // 鼠标释放事件
    canvas.addEventListener('mouseup', function() {
        isDragging = false;
        isResizing = false;
    });

    // 鼠标离开画布事件
    canvas.addEventListener('mouseleave', function() {
        isDragging = false;
        isResizing = false;
    });

    // 添加键盘事件监听器 - 删除选中的贴纸
    document.addEventListener('keydown', function(e) {
        if (!currentImage || !selectedSticker) return;

        // 检查是否按下 Delete 或 Back Space 键
        if (e.key === 'Delete' || e.key === 'Backspace') {
            // 从数组中移除选中的贴纸
            currentStickers = currentStickers.filter(sticker => sticker.id !== selectedSticker.id);
            // 重置选中状态
            selectedSticker = null;
            // 重绘画布
            redrawCanvas();
        }
    });

    // 完成按钮点击事件
    completeBtn.click(function() {
        if (!currentImage) return;

        // 创建下载链接
        const dataURL = canvas.toDataURL('image/jpeg', 1.0);
        const link = document.createElement('a');
        link.href = dataURL;
        link.download = 'edited-image-' + Date.now() + '.jpg';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });

    // 初始化
    initCanvas();
});